package com.event.management.frontend.controller;

import com.event.management.frontend.common.Result;
import com.event.management.frontend.dto.QuestionnaireDTO;
import com.event.management.frontend.dto.QuestionnaireAnswerDTO;
import com.event.management.frontend.service.QuestionnaireService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.dev33.satoken.stp.StpUtil;

/**
 * 问卷控制器
 */
@Api(tags = "问卷接口")
@RestController
@RequestMapping("/api/front/questionnaire")
@RequiredArgsConstructor
@Slf4j
public class QuestionnaireController {

    private final QuestionnaireService questionnaireService;
    
    /**
     * 获取活动关联的随机问卷
     * @param eventId 活动ID
     * @return 问卷信息
     */
    @ApiOperation("获取活动关联的随机问卷")
    @GetMapping("/events/{eventId}/random")
    public Result<QuestionnaireDTO> getRandomQuestionnaire(
            @ApiParam("活动ID") @PathVariable Long eventId) {
        log.info("获取活动[{}]关联的随机问卷", eventId);
        
        QuestionnaireDTO questionnaire = questionnaireService.getRandomQuestionnaireByEventId(eventId);
        if (questionnaire == null) {
            return Result.ok(null, "该活动没有关联问卷");
        }
        
        return Result.ok(questionnaire);
    }
    
    /**
     * 提交问卷答案
     * @param answerDTO 问卷答案
     * @return 提交结果
     */
    @ApiOperation("提交问卷答案")
    @PostMapping("/answers")
    public Result<Boolean> submitQuestionnaireAnswer(
            @ApiParam("问卷答案") @RequestBody QuestionnaireAnswerDTO answerDTO) {
        log.info("提交问卷答案，问卷ID: {}, 活动ID: {}, 电子票ID: {}", 
                answerDTO.getQuestionnaireId(), answerDTO.getEventId(), answerDTO.getUserTicketId());
        
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 保存答案并标记电子票
        boolean success = questionnaireService.saveQuestionnaireAnswer(userId, answerDTO);
        
        if (success) {
            return Result.ok(true, "问卷提交成功");
        } else {
            return Result.fail("问卷提交失败");
        }
    }
} 